import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/expert/top/top_list_logic.dart';
import 'package:sports_new/entity/expert/expert_top_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/expert/items/expert_first_tag.dart';
import 'package:sports_new/widgets/circular.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/focus_button.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';
import 'package:sports_new/widgets/loading/shimmer_loading_widget.dart';
import '../../../widgets/base/qkd_text.dart';

enum TopType { renqi, mingzhong, huibao, lianhong, saishi }

class TopListView extends StatefulWidget {
  final TopType type;
  final int sportsId;
  final ScrollPhysics physics;
  final bool? onlySale;
  const TopListView(this.type, this.sportsId,
      {super.key, required this.physics, this.onlySale});

  @override
  State<TopListView> createState() => _TopListViewState();
}

class _TopListViewState extends State<TopListView> {
  late TopListLogic logic;

  @override
  void initState() {
    super.initState();
    logic = Get.put(TopListLogic(widget.type, widget.sportsId),
        tag: '${widget.sportsId}${widget.type}');
    if (widget.onlySale != null) logic.onlySale = widget.onlySale!;
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<TopListLogic>(
      tag: '${widget.sportsId}${widget.type}',
      builder: (_) {
        return Column(
          children: [
            // SizedBox(height: 8),
            if (logic.condition != null) condition(),
            Expanded(
                child: LoadingWidget<bool>(
                    isLoading: logic.list == null,
                    loading: SingleChildScrollView(
                      child: Column(
                        children: [
                          shimmerTop(),
                          ...List.generate(15, (index) => shimmerItem())
                        ],
                      ),
                    ),
                    data: logic.list?.length == 0,
                    noData: NoDataWidget(
                      needScroll: true,
                      physics: widget.physics,
                      tip: '暂无排名，去全部专家看看吧~',
                      buttonText: '查看全部专家',
                      onTap: () => Get.toNamed(Routes.expertAll,
                          arguments: widget.sportsId == 1 ? 0 : 1),
                    ),
                    child: () => list()))
          ],
        );
      },
    );
  }

  Widget condition() {
    double buttonWidth = 61;
    if (logic.type == TopType.lianhong) {
      buttonWidth = 80;
    }
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Row(
        children: [
          ...List.generate(logic.condition!.length, (index) {
            return QkdButton(
                    text: logic.condition![index].name,
                    backgroundColor: logic.conditionIndex == index
                        ? Colours.main
                        : Colours.greyF7,
                    textStyle: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w400,
                        color: logic.conditionIndex == index
                            ? Colours.white
                            : Colours.grey66),
                    width: buttonWidth,
                    height: 24,
                    onPressed: () => logic.onTapCondition(index))
                .marginOnly(right: 8);
          }),
          const Spacer(),
          QkdButton(
              // width: 70,
              height: 24,
              widget:
                  Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                Image.asset(
                  Utils.getImgPath(
                      logic.onlySale ? 'check.png' : 'uncheck.png'),
                  width: 14,
                  height: 14,
                ),
                const SizedBox(width: 2),
                const QkdText(
                  '只看在售',
                  color: Colours.grey66,
                ),
              ]),
              onPressed: logic.onTapFilter),
        ],
      ),
    );
  }

  Widget list() {
    return CustomScrollView(
      physics: widget.physics,
      slivers: [
        // const HeaderLocator.sliver(),
        SliverToBoxAdapter(
          child: Padding(
            padding: const EdgeInsets.fromLTRB(0, 4, 0, 12),
            child: Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  logic.list!.length >= 2
                      ? top3Widget(2)
                      : Container(width: 110),
                  SizedBox(width: (Get.width - 330) / 5),
                  logic.list!.isNotEmpty
                      ? top3Widget(1)
                      : Container(width: 110),
                  SizedBox(width: (Get.width - 330) / 5),
                  logic.list!.length >= 3
                      ? top3Widget(3)
                      : Container(width: 110)
                ]),
          ),
        ),
        SliverList.builder(
          itemBuilder: (context, index) => cell(index),
          itemCount: logic.list!.length - 3,
        ),
        SliverToBoxAdapter(
          child: GestureDetector(
            onTap: () {
              Get.toNamed(Routes.expertAll,
                  arguments: widget.sportsId == 1 ? 0 : 1);
            },
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const QkdText('查看全部专家',
                      needCenter: true, fontSize: 12, color: Colours.grey66),
                  Image.asset(
                    Utils.getImgPath('arrow_right_36.png'),
                    width: 12,
                  )
                ],
              ),
            ),
          ),
        ),
        SliverToBoxAdapter(child: Container(height: 62))
      ],
    );
  }

  Widget cell(int index) {
    ExpertTopEntity data = logic.list![index + 3];
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
          child: Row(children: [
            QkdText('${index + 4}', fontSize: 13),
            const SizedBox(width: 16),
            ClipOval(
              child: CachedNetworkImage(
                imageUrl: data.userLogo ?? '',
                width: 32,
                height: 32,
                fit: BoxFit.cover,
              ),
            ),
            const SizedBox(width: 8),
            QkdText('${data.userName}',
                needCenter: true, fontWeight: FontWeight.w500),
            Container(width: 4),
            if (ModeConfig.expertRecord && data.value.hasValue)
              ExpertFirstTag(tag: data.value!),
            const Spacer(),
            FocusButton(
              data.isFocus ?? 0,
              userId: data.userId,
              onTap: (p0) {
                data.isFocus = p0;
                Utils.onEvent("expert_rank_follow",
                    params: {"expert_id": data.userId, "follow": p0});
              },
            )
          ]),
        ).tap(() {
          toExpertPage(data);
        }),
        Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          color: Colours.greyEE,
          height: 0.5,
          width: double.infinity,
        )
      ],
    );
  }

  Widget top3Widget(int rank) {
    double height = 238;
    late ExpertTopEntity data;
    Color color = const Color(0xFFF65252).withOpacity(0.8);
    Color borderColor = const Color(0xFFFDC946);
    Color right = const Color(0xFFFEC230);
    Color left = const Color(0xFFFDDD74);
    Color textShadow = const Color(0xFFE78853);
    String img = 'expert_top1.png';
    if (rank == 1) {
      data = logic.list![0];
    } else if (rank == 2) {
      height = 216;
      color = const Color(0xFFF65252).withOpacity(0.45);
      data = logic.list![1];
      borderColor = const Color(0xFF98B0C8);
      img = 'expert_top2.png';
      right = const Color(0xFFA4CCD3);
      left = const Color(0xFFBAE1E9);
      textShadow = const Color(0xFF5C99A4);
    } else if (rank == 3) {
      height = 216;
      color = const Color(0xFFF65252).withOpacity(0.25);
      data = logic.list![2];
      borderColor = const Color(0xFFDCAF6F);
      img = 'expert_top3.png';
      right = const Color(0xFFBB8026);
      left = const Color(0xFFEBB25A);
      textShadow = const Color(0xFFBC773D);
    }
    return Stack(
      alignment: Alignment.bottomCenter,
      children: [
        Stack(
          alignment: Alignment.topCenter,
          children: [
            Container(
              width: 110,
              height: height,
              margin: const EdgeInsets.only(top: 18),
              decoration: BoxDecoration(
                  borderRadius:
                      const BorderRadius.vertical(top: Radius.circular(55)),
                  gradient: LinearGradient(
                    colors: [color, Colors.white],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                  )),
              child: Column(children: [
                const SizedBox(height: 13),
                Container(
                  decoration: BoxDecoration(
                      border: Border.all(color: borderColor),
                      borderRadius: BorderRadius.circular(37)),
                  child: ClipOval(
                    child: CachedNetworkImage(
                      imageUrl: data.userLogo ?? '',
                      width: 74,
                      height: 74,
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                const SizedBox(height: 23),
                QkdText(data.userName ?? '', maxLines: 1),
                if (ModeConfig.expertRecord) ...[
                  const SizedBox(height: 2),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        height: 18,
                        padding: const EdgeInsets.symmetric(horizontal: 6),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            gradient: LinearGradient(colors: [left, right]),
                            borderRadius: const BorderRadius.only(
                                topRight: Radius.circular(4),
                                bottomLeft: Radius.circular(4),
                                bottomRight: Radius.circular(4))),
                        child: QkdText(
                          data.value ?? "",
                          needCenter: true,
                          color: Colours.white,
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                          shadows: [
                            Shadow(
                                color: textShadow, offset: const Offset(0, 0.6))
                          ],
                        ),
                      ),
                    ],
                  )
                ],
                Container(height: 12),
                FocusButton(
                  data.isFocus ?? 0,
                  userId: data.userId,
                  onTap: (p0) {
                    data.isFocus = p0;
                    Utils.onEvent("expert_rank_follow",
                        params: {"expert_id": data.userId, "follow": p0});
                  },
                )
              ]),
            ),
            Positioned(
                top: 66 + 18,
                child: Image.asset(
                  Utils.getImgPath(img),
                  width: 32,
                ))
          ],
        ),
        if (rank == 1)
          Positioned(
              top: 4,
              child: Image.asset(
                Utils.getImgPath('expert_champion.png'),
                width: 32,
              ))
      ],
    ).tap(() {
      toExpertPage(data);
    });
  }

  toExpertPage(ExpertTopEntity data) async {
    Utils.onEvent("expert_rank_expert_view",
        params: {"expert_id": data.userId});
    await Get.toNamed(Routes.userPage,
        arguments: data.userId,
        parameters: {'type': '1', 'index': widget.sportsId == 1 ? 'zq' : 'lq'});
    logic.onRefresh();
  }

  Widget shimmerTop() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 4, 0, 12),
      child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          mainAxisAlignment: MainAxisAlignment.center,
          children: List<Widget>.generate(
              3,
              (index) => Padding(
                    padding: const EdgeInsets.only(top: 18),
                    child: Stack(
                      children: [
                        Opacity(
                          opacity: 0.3,
                          child: Container(
                            height: index == 1 ? 209 : 188,
                            width: 110,
                            decoration: const BoxDecoration(
                                borderRadius: BorderRadius.vertical(
                                    top: Radius.circular(55)),
                                gradient: LinearGradient(
                                  colors: [Colours.greyCC, Colours.transparent],
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter,
                                ),
                                boxShadow: [
                                  BoxShadow(
                                      color: Color(0x0A0F499F),
                                      offset: Offset(0, 2),
                                      blurRadius: 12)
                                ]),
                          ),
                        ),
                        const Positioned.fill(
                          child: Column(
                            children: [
                              SizedBox(height: 13),
                              ShimmerLoading(
                                  width: 74,
                                  height: 74,
                                  shape: BoxShape.circle),
                              Spacer(),
                              ShimmerLoading(width: 49, height: 19, radius: 2),
                              SizedBox(height: 12),
                              ShimmerLoading(width: 58, height: 24, radius: 4)
                            ],
                          ),
                        )
                      ],
                    ),
                  )).insertEvery(SizedBox(width: (Get.width - 330) / 5))),
    );
  }

  Widget shimmerItem() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
          child: const Row(children: [
            QkdText('0', fontSize: 13, color: Colours.transparent),
            SizedBox(width: 16),
            ShimmerLoading(width: 32, height: 32, shape: BoxShape.circle),
            SizedBox(width: 8),
            ShimmerLoading(width: 69, height: 19),
            Spacer(),
            ShimmerLoading(width: 56, height: 24, radius: 4)
          ]),
        ),
        Divider(color: Colours.greyCC.withOpacity(0.2), height: 0.5)
            .paddingSymmetric(horizontal: 16)
      ],
    );
  }
}
